<template>
  <layout-card :filters="exampleOptions" headline="拾捡物品公示" @search-change="searchChange" @search-reset="searchReset">
    <template v-if="taskProcess === '过期处置' && tableData.length > 0" #action>
      <el-button @click="handleShowBatchDisposal" type="primary">批量处置</el-button>
    </template>

    <div class="table-common">

      <el-radio-group v-model="taskProcess" style="margin-bottom: 30px">
        <el-radio-button label="过期处置">
          待处置
          <span class="badge" v-if="disposalCount.expired > 0">{{ disposalCount.expired }}</span>
        </el-radio-button>
        <el-radio-button label="处置审批">
          待审批
          <span class="badge" v-if="disposalCount.approval > 0">{{ disposalCount.approval }}</span>
        </el-radio-button>
        <el-radio-button label="回收站">
          已通过
          <!-- <span class="badge" v-if="disposalCount.bin > 0">{{ disposalCount.bin }}</span> -->
        </el-radio-button>
        <el-radio-button label="处置审批驳回">
          已驳回
          <span class="badge" v-if="disposalCount.rejection > 0">{{ disposalCount.rejection }}</span>
        </el-radio-button>
        <!-- <el-badge hidden :value="0" :max="99" class="item">
          <el-radio-button label="处置审批驳回">已驳回</el-radio-button>
        </el-badge> -->
      </el-radio-group>
    </div>
    <!-- 列表 -->
    <div class="goods" v-loading="loading">
      <div class="goods_content" v-for="(item, index) in tableData" :key="index" @click="gooodsClick(item)">
        <img :src="item?.goodsFiles ? item?.goodsFiles?.[0]?.resourceAddress : image.noImg" class="image" />
        <div class="message">
          <div class="message_content">
            <div class="type" :title="item['goodsName']">{{ item['goodsName'] }}</div>
            <!-- <div class="terminal">{{ item['taskProcess'] }}</div> -->
          </div>
          <div class="message_content" style="margin-top: 8px;">
            <div class="headline">物品类型：</div>
            <div class="headline_content">{{ getGoodsTypeName(item?.goodsType) }}</div>
          </div>
          <div class="message_content" style="margin-top: 4px;">
            <div class="headline">捡拾日期：</div>
            <div class="headline_content">{{ formatTime(item['pickUpTime'], 'YYYY-MM-DD') }}</div>
          </div>
          <div class="message_content" style="margin-top: 4px;">
            <div class="headline">捡拾地：</div>
            <div class="headline_content">{{ item['pickUpPlace'] }}</div>
          </div>
          <div class="message_content" style="margin-top: 4px;">
            <div class="headline">物品编号：</div>
            <div class="headline_content">{{ item['goodsCode'] }}</div>
          </div>
          <div class="message_content" v-if="taskProcess === '处置审批驳回'" style="margin-top: 4px;">
            <div class="headline">驳回原因:</div>
            <div class="headline_content" :title="item['nodeContentObj']['remarks'] || ''">{{ item['nodeContentObj']['remarks'] || '' }}</div>
          </div>
        </div>


        <el-button v-if="taskProcess === '过期处置'" class="status-btn" size="small" type="danger" plain>已过期</el-button>
        <el-button v-if="taskProcess === '处置审批'" class="status-btn" size="small" type="danger" plain>待审批</el-button>

        <div class="btn-group" v-if="taskProcess === '过期处置'">
          <el-button @click.stop="handleClaimClick(item)">领取</el-button>
          <el-button @click.stop="handleDisposeClick(item)" type="primary">处置</el-button>
        </div>

        <div class="btn-group" v-if="taskProcess === '处置审批驳回'">
          <el-button @click.stop="handleDisposeClick(item)" type="primary">重新申请处置</el-button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div>
      <TablePagination :small="false" :pagination="pager" @current-change="currentChange" @size-change="sizeChange" />
    </div>

    <edit-dialog :centerDialogVisible="centerDialogVisible" :tilte="tilte" @Cancel="Cancel" :defaultButton="defaultButton"
      @Submit="Submit(goodsTypeFormRef)" :width="dialogWidth">
      <template #content>
        <el-form ref="goodsTypeFormRef" :rules="rules" :model="form" label-width="110px">

          <!-- 领取 -->
          <template v-if="tilte === '领取物品'">
            <el-form-item label="领取人姓名" prop="receiveName">
              <el-input v-model="form.receiveName" />
            </el-form-item>
            <el-form-item label="领取人证件号" prop="receiveNo">
              <el-input v-model="form.receiveNo" />
            </el-form-item>
            <el-form-item label="领取人电话" prop="receivePhone">
              <el-input v-model="form.receivePhone" />
            </el-form-item>
            <el-form-item label="领取时间" prop="receiveTime">
              <el-date-picker v-model="form.receiveTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"/>
            </el-form-item>
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" :rows="5" maxlength="200" show-word-limit type="textarea" />
            </el-form-item>
          </template>

          <!-- 出库申请 -->

          <!-- 处置物品 -->

          <!-- 处置审批驳回 -->
          <template v-if="tilte === '过期物品详情'">
            <div class="dispose-container">
              <div class="title">物品信息</div>
              <div class="content">
                <el-carousel v-if="goodsObject?.goodsFiles?.length > 0" height="240px">
                  <el-carousel-item v-for="item in goodsObject?.goodsFiles" :key="item">
                    <img :src="item ? item?.resourceAddress : image.noImg" />
                  </el-carousel-item>
                </el-carousel>
                <img v-else
                  :src="goodsObject?.goodsFiles ? goodsObject?.goodsFiles?.[0]?.resourceAddress : image.noImg" />
                <div class="info">
                  <div class="item">
                    <div class="label">物品名称</div>
                    <div class="value" :title="goodsObject?.goodsName || ''">{{ goodsObject?.goodsName || '' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">物品类型</div>
                    <div class="value">{{ getGoodsTypeName(goodsObject?.goodsType) || '' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">物品编号</div>
                    <div class="value">{{ goodsObject?.goodsCode || '' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">捡拾日期</div>
                    <div class="value">{{ formatTime(goodsObject?.pickUpTime) || '' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">保质期</div>
                    <div class="value">
                      {{ goodsData?.timeLimit || '0' }}
                      {{ getUnit(goodsData?.timeLimitUnit) || '' }}
                    </div>
                  </div>
                  <div class="item">
                    <div class="label">物品时效</div>
                    <div class="value">{{ goodsData?.goodsLimitTime ? formatTime(goodsData?.goodsLimitTime, 'YYYY-MM-DD HH:mm:ss'):'' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">捡拾人姓名</div>
                    <div class="value">{{ goodsData?.pickUpName || '' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">捡拾人电话</div>
                    <div class="value">{{ goodsData?.pickUpPhone || '' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">航站楼【捡拾】</div>
                    <div class="value">{{ goodsData?.pickUpTerminal || '' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">捡拾地</div>
                    <div class="value">{{ goodsData?.pickUpPlace || '' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">航站楼【存放】</div>
                    <div class="value">{{ goodsData?.depositTerminal || '' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">存放地</div>
                    <div class="value">{{ getName('depositPlace',goodsData?.depositPlace || '') }}</div>
                  </div>
                  <div class="item">
                    <div class="label">登记人</div>
                    <div class="value">{{ goodsData?.creator?.name || '' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">登记时间</div>
                    <div class="value">{{ formatTime(goodsData?.createTime) || '' }}</div>
                  </div>
                </div>
              </div>

              <template v-if="taskProcess !== '过期处置'">
                <div class="title">处置信息</div>
                <div class="info2">
                  <div class="item">
                    <div class="label">处置人</div>
                    <div class="value">{{ nodeContentExpireObj?.nodeUserName || '' }}</div>
                    <!-- <div class="value">{{ goodsData?.creator?.name || '' }}</div> -->
                  </div>
                  <div class="item">
                    <div class="label">处置时间</div>
                    <!-- <div class="value">{{ formatTime(goodsObject?.lastUpdateTime) || '' }}</div> -->
                    <div class="value">{{ nodeContentExpireObj?.nodeTime ? formatTime(nodeContentExpireObj?.nodeTime) : '' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">处置原因</div>
                    <div class="value" :title="nodeContentExpireObj?.nodeContent?.remarks">{{ nodeContentExpireObj?.nodeContent?.remarks || '' }}</div>
                  </div>
                </div>
              </template>

              <template v-if="rejectShowRemark">
                <div class="title">审批意见</div>
                <el-form-item label="审批意见" prop="remarks">
                  <el-input v-model="form.remarks" :rows="5" maxlength="200" show-word-limit type="textarea" />
                </el-form-item>
              </template>

              <template v-if="taskProcess === '处置审批驳回'">
                <div class="title">审批信息</div>
                <div class="info2">
                  <div class="item">
                    <div class="label">审批人</div>
                    <div class="value">{{ nodeContentRejectObj?.nodeUserName || '' }}</div>
                  </div>
                  <div class="item">
                    <div class="label">审批时间</div>
                    <div class="value">{{ nodeContentRejectObj?.nodeTime ? formatTime(nodeContentRejectObj?.nodeTime) : ''
                    }}</div>
                  </div>
                  <div class="item">
                    <div class="label">审批意见</div>
                    <div class="value" :title="nodeContentRejectObj?.nodeContent?.remarks">{{ nodeContentRejectObj?.nodeContent?.remarks || '' }}</div>
                  </div>
                </div>
              </template>

            </div>
          </template>

          <!-- 处置过期 -->
          <template v-if="tilte === '过期物品处置'">
            <el-form-item label="处置原因" prop="remarks">
              <el-input v-model="form.remarks" :rows="5" maxlength="200" show-word-limit type="textarea" />
            </el-form-item>
          </template>

          <template v-if="tilte === '过期物品批量处置'">
            <div class="batch-check-list">
              <div class="item" :class="selectid.includes(item.taskId) ? 'select' : ''" v-for="(item, index) in tableData"
                :key="item.taskId" @click="handleBatchSelect(item)">
                <img :src="item?.goodsFiles ? item?.goodsFiles?.[0]?.resourceAddress : image.noImg" />
                <div class="info">
                  <div class="title" :title="item['goodsName']">{{ item?.goodsName || '' }}</div>
                  <div class="row">
                    <div class="label">物品类型：</div>
                    <div class="value">{{ getGoodsTypeName(item?.goodsType) || '' }}</div>
                  </div>
                  <div class="row">
                    <div class="label">捡拾日期：</div>
                    <div class="value">{{ formatTime(item?.pickUpTime, "YYYY-MM-DD") || '' }}</div>
                  </div>
                  <div class="row">
                    <div class="label">捡拾地：</div>
                    <div class="value">{{ item?.pickUpPlace || '' }}</div>
                  </div>
                  <div class="row">
                    <div class="label">物品编号：</div>
                    <div class="value">{{ item?.goodsCode || '' }}</div>
                  </div>
                </div>
                <div class="check">
                  <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" data-v-ea893728="">
                    <path fill="currentColor"
                      d="M406.656 706.944 195.84 496.256a32 32 0 1 0-45.248 45.248l256 256 512-512a32 32 0 0 0-45.248-45.248L406.592 706.944z">
                    </path>
                  </svg>
                </div>
              </div>
            </div>

            <el-form-item label="处置原因" prop="remarks">
              <el-input v-model="form.remarks" :rows="5" maxlength="200" show-word-limit type="textarea" />
            </el-form-item>

            <div>
              <TablePagination :small="false" :pagination="pager" @current-change="currentChange"
                @size-change="sizeChange" />
            </div>

          </template>

        </el-form>



      </template>
      <template #custom>
        <span class="dialog-footer">
          <template v-if="taskProcess === '处置审批'">
            <el-button class="buttonCancel" @click="centerDialogVisible = false">取消</el-button>
            <template v-if="rejectShowRemark">
              <el-button class="buttonOverdue" @click="handleReject(goodsTypeFormRef)" type="primary">确定</el-button>
            </template>
            <template v-else>
              <el-button class="buttonOverdue" @click="handleReject(goodsTypeFormRef)" type="danger" plain>驳回</el-button>
              <el-button class="buttonOverdue" @click="handleAdopt" type="primary">通过</el-button>
            </template>
          </template>
        </span>
      </template>
    </edit-dialog>

  </layout-card>
</template>
<script lang="ts" setup>
import dayjs from 'dayjs';
import { image } from '@/assets/index'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import LayoutCard from '@/components/LayoutCard/index.vue'
import { ref, reactive, onBeforeMount, onBeforeUnmount, computed, watch } from 'vue'
import { goodsTypeList } from '@/api/lose/goodsType'
import { processComplete } from '@/api/common'
import TablePagination from '@/components/TablePagination/index.vue'
import { getResource } from '@/api/resource'
import { getGoodsRegList, getGoodsRegFind, getGoodsRegAcceptList, pickUpGoodsDetail, receiveGoodsReg } from '@/api/lose/goodsDerelict';
import editDialog from '@/components/editDialog/index.vue'

interface SearchType {
  startTime?: String;
  endTime?: String[];
  goodsType?: String;
  classifyCode?: String;
}

interface GoodsTypeState {
  typeId: string;
  goodsType: string;
  classifyCode: string;
  timeLimit: string;
  timeLimitUnit: string;
  remarks: string;
}

interface RuleForm {
  receiveName: string;
  receiveTime: string;
  receiveNo: string;
  receivePhone: string;
  remarks: string;
}

const store = useStore()
const userInfo = computed(() => store.state.user.userInfo)

// 弹窗是否打开
const centerDialogVisible = ref(false)
// 弹窗标题
const tilte = ref('新增')
const goodsData = ref()
const goodsObject = ref()
const nodeContentObj = ref()
const nodeContentRejectObj = ref()
const nodeContentExpireObj = ref()
const nodeContentReceivedObj = ref()
const dialogWidth = ref('760px')
const defaultButton = ref(true)
const selectid = ref<string[]>([])

const placeData = ref([]) // 存放地址
const typeData = ref([])
const timer = ref()
const terminalData = ref([] as any[]) // 航站

// 是否显示审批意见
const rejectShowRemark = ref(false);


const dialogStatus = ref('详情')

const goodsTypeFormRef = ref<FormInstance>()
const form = reactive<RuleForm>({
  receiveName: '',
  receiveTime: '',
  receiveNo: '',
  receivePhone: '',
  remarks: '',
})

const validatorNo = (rule: any, value: any, callback: any) => {
  if (!value) return callback(new Error('请输入领取人身份证号！'))
  if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)) return callback(new Error('保存实现应为数字（最多两位小数）'))
  callback()
}

const validatorPhone = (rule: any, value: any, callback: any) => {
  if (!value) return callback(new Error('请输入电话号码！'))
  if (!/^1\d{10}$/.test(value)) return callback(new Error('电话号码格式不正确！'))
  callback()
}

const rules = reactive<FormRules<RuleForm>>({
  receiveName: [{ required: true, message: '请输入领取人姓名', trigger: 'change' }],
  receiveTime: [{ required: true, message: '请选择领取时间', trigger: 'change' }],
  // receiveNo: [{ required: true, validator: validatorNo, message: '请输入保存时限', trigger: 'change' }],
  receivePhone: [{ required: true, validator: validatorPhone, message: '请输入领取人电话', trigger: 'change' }],
  remarks: [],
})

const taskProcess = ref('过期处置')
const variablesSwitch = ref(1)
const loading = ref(false)
const tableData = ref<any[]>([])
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const disposalCount = reactive({
  expired: 0,
  approval: 0,
  bin: 0,
  rejection: 0,
})

// 查询条件
const exampleOptions = ref([
  {
    label: '物品名称',
    prop: 'goodsName',
    type: 'input',
    inputProps: {
      clearable: true,
      placeholder: '请输入物品名称'
    }
  },
  {
    label: '物品编号',
    prop: 'goodsCode',
    type: 'input',
    inputProps: {
      clearable: true,
      placeholder: '请输入物品编号'
    }
  },
  {
    label: '过期时间',
    prop: 'guoqi',
    type: 'datePicker',
    defaultValue: [],
    inputProps: {
      type: 'daterange',
      'value-format': 'YYYY-MM-DD HH:ss:mm'
    }
  },
  {
    label: '拾捡时间',
    prop: 'shiqu',
    type: 'datePicker',
    defaultValue: [],
    inputProps: {
      type: 'daterange',
      'value-format': 'YYYY-MM-DD HH:ss:mm'
    }
  },
  {
    label: '物品类型',
    prop: 'goodsType',
    type: 'select',
    defaultValue: '',
    inputProps: {
      showCheckAll: true,
      options: [
        { label: '全部', value: '' },
      ]
    }
  },
  {
    label: '存放航站楼',
    prop: 'storeTerminal',
    type: 'checkbox',
    defaultValue: [],
    inputProps: {
      options: [
      ]
    }
  },
  {
    label: '存放位置',
    prop: 'storePosition',
    type: 'checkbox',
    defaultValue: [''],
    span: 16,
    inputProps: {
      options: [
      ]
    }
  },
])

// 分页
const sizeChange = (size: number) => {
  pager.pageSize = size
  loadData()
}

const currentChange = (value: number) => {
  pager.currentPage = value
  loadData()
}

const search = ref<SearchType>({})
const loadData = async () => {
  loading.value = true;
  const payload: any = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: {}
  }
  if (search.value.guoqi && search.value.guoqi?.length > 0) {
    payload.condition.startLimitTime = search.value.guoqi[0] || '';
    payload.condition.endLimitTime = search.value.guoqi[1] || '' ? dayjs(search.value.guoqi[1] || '').format('YYYY-MM-DD 23:59:59') : '';
  }
  if (search.value.shiqu && search.value.shiqu?.length > 0) {
    payload.condition.startTime = search.value.shiqu[0] || '';
    payload.condition.endTime = search.value.shiqu[1] || '' ? dayjs(search.value.shiqu[1] || '').format('YYYY-MM-DD 23:59:59') : '';
  }
  if (search.value.classifyCode) {
    payload.condition.classifyCode = search.value.classifyCode || '';
  }
  if (search.value.goodsType && search.value.goodsType?.length > 0) {
    payload.condition.goodsType = search.value.goodsType;
  }
  payload.condition.taskProcess = taskProcess.value || '';
  payload.condition.goodsName = search.value.goodsName || '';
  payload.condition.goodsCode = search.value.goodsCode || '';
  if (search.value.storeTerminal && search.value.storeTerminal.length > 0) {
    payload.condition.storeTerminal = search.value.storeTerminal.join(",");
  }
  payload.condition.storePosition = search.value.storePosition?.[0] || '';
  // ...获取数据
  const res: any = await getGoodsRegList(payload);
  loading.value = false
  if (res && res.code === '1') {
    tableData.value = res?.data?.list.map((item: any) => {
      try {
        item.nodeContentObj = JSON.parse(item.nodeContent)
      } catch (error) {
        console.error(error)
      }
      try {
        item.taskContentObj = JSON.parse(item.taskContent)
      } catch (error) {
        console.error(error)
      }
      return item
    })
    pager.total = res?.data?.total
    console.log(tableData.value)
  } else {
    tableData.value = [];
    ElMessage.error(res?.message || '获取列表失败，请刷新重试！')
  }
}

const formatTime = (str: string, YMD = 'YYYY-MM-DD HH:mm:ss') => {
  if (!str) return '';
  return dayjs(str).format(YMD)
}

/**
* 点击查询
*/
const searchChange = (data: FilterDataType) => {
  search.value = data
  loadData()
}
/**
* 点击重置
* @param data 数据
*/
const searchReset = (data: FilterDataType) => {
  search.value = data
  pager.currentPage = 1
  pager.pageSize = 10
  loadData()
}

const loadDict = () => {
  // 存放地
  getResource('lose_deposit_place').then((res: any) => {
    if (res?.code === '1') {
      if (res && res.data) {
        let list = res.data?.properties?.meta || []
        exampleOptions.value[6].inputProps.options = [ ...list]
      }
    }
  })
  // 航站楼
  getResource('terminal').then((res: any) => {
    if (res?.code === '1') {
      if (res && res.data) {
        let list = res.data?.properties?.meta || []
        exampleOptions.value[5].inputProps.options = [...list]
      }
    }
  })
}

// 物品类型
const queryGoodsTypeFind = () => {
  goodsTypeList({}).then((res: any) => {
    if (res?.code === '1') {
      if (res && res.data) {
        const { data } = res
        exampleOptions.value[4].inputProps.options = [
          { label: '全部', value: '' }, ...data.map((item: any) => ({ label: item.goodsType, value: item.typeId }))]
      }
    }
  })
}

const getGoodsTypeName = (typeId = '') => {
  console.log(typeId, exampleOptions.value[4].inputProps.options)
  let name = '';
  exampleOptions.value[4].inputProps.options?.forEach((item) => {
    if (item.value == typeId) {
      name = item.label
    }
  })
  return name;
}

/**
 * 卡片点击事件
 */

const gooodsClick = async (info: any) => {
  form.remarks = '';
  if (goodsTypeFormRef.value?.resetFields) goodsTypeFormRef.value?.resetFields();
  // if (taskProcess.value === '处置审批') {
  goodsObject.value = info;
  // info?.list?.forEach(item => {
  //   if (item.taskProcess === '处置审批') {
  //     nodeContentObj.value = item;
  //   }
  // })
  centerDialogVisible.value = true
  rejectShowRemark.value = false;
  defaultButton.value = false;
  tilte.value = '过期物品详情'
  dialogWidth.value = '1000px'
  const res = await pickUpGoodsDetail({ regId: info.regId, taskId: info.taskId })
  if (res?.code === '1') {
    goodsData.value = res?.data?.goodsData;
    nodeContentObj.value = null;
    nodeContentRejectObj.value = null;
    nodeContentExpireObj.value = null;
    nodeContentReceivedObj.value = null;
    res?.data?.list?.reverse().forEach(item => {
      if (!nodeContentObj.value && item.nodeName === '处置审批') {
        nodeContentObj.value = {
          ...item,
          nodeContent: JSON.parse(item?.nodeContent)
        }
      }
      if (!nodeContentRejectObj.value && item.nodeName === '处置审批驳回') {
        nodeContentRejectObj.value = {
          ...item,
          nodeContent: JSON.parse(item?.nodeContent)
        }
      }
      if (!nodeContentExpireObj.value && item.nodeName === '过期处置') {
        nodeContentExpireObj.value = {
          ...item,
          nodeContent: JSON.parse(item?.nodeContent)
        }
      }
      if (!nodeContentReceivedObj.value && item.nodeName === '已接收') {
        nodeContentReceivedObj.value = {
          ...item,
          nodeContent: JSON.parse(item?.nodeContent)
        }
      }
    })
    // nodeContentObj.value = {
    //   ...res?.data?.list[0],
    //   nodeContent: JSON.parse(res?.data?.list[0]?.nodeContent)
    // }
  }
}

const handleClaimClick = (info: any) => {
  goodsObject.value = info;
  tilte.value = '领取物品'
  centerDialogVisible.value = true
  defaultButton.value = true;
  dialogWidth.value = '500px'
  variablesSwitch.value = 1
  dialogStatus.value = "领取"
  rules.remarks = []
}

const handleDisposeClick = (info: any) => {
  goodsObject.value = info;
  tilte.value = '过期物品处置'
  centerDialogVisible.value = true
  defaultButton.value = true;
  dialogWidth.value = '500px'
  variablesSwitch.value = 3
  dialogStatus.value = "处置"
  rules.remarks = [{ required: true, message: () => rejectShowRemark.value ? '请输入审批意见' : '请输入处置原因', trigger: 'change' }]
}

/**
* 获取字典数据
*/
const loadDict2 = async () => {
  let placeRes = await getResource('lose_deposit_place'); // 加载存放地数据字典
  let terminalRes = await getResource('terminal') // 加载航站楼数据字典
  let places = placeRes?.data?.properties?.meta || []
  let terminals = terminalRes?.data?.properties?.meta || []
  placeData.value = places
  terminalData.value = terminals
}

/**
 * 弹窗点击取消
 */
const Cancel = () => {
  rejectShowRemark.value = false;
  centerDialogVisible.value = false;

  form.receiveName = '';
  form.receiveTime = '';
  form.receiveNo = '';
  form.receivePhone = '';
  form.remarks = '';
}

/**
 * 弹窗点击确认 领取 处置
 */
const Submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let fetch = null;
      let payload: any = {}
      if (tilte.value === '领取物品') {
        // 领取
        fetch = receiveGoodsReg;
        payload = {
          ...form,
          taskId: goodsObject.value?.taskId || "",
          creator: {
            id: userInfo.value.userId,
            name: userInfo.value.name,
            userName: userInfo.value.userName,
            organId: userInfo.value.organId || '',
            organName: userInfo.value.organName || ''
          },
          regId: goodsObject.value?.regId || ""
        }
      } else {
        // 处置
        fetch = processComplete;
        payload = {
          content: {
            ...form,
            taskId: goodsObject.value?.taskId || "",
            creator: {
              id: userInfo.value.userId,
              name: userInfo.value.name,
              userName: userInfo.value.userName,
              organId: userInfo.value.organId || '',
              organName: userInfo.value.organName || ''
            },
          },
          id: goodsObject.value?.taskId,
          variables: {
            switch: variablesSwitch.value, // 排他网关 1：领取物品，流程节点状态更改为已领取
          }
        }
      }

      if (tilte.value === '过期物品批量处置') {
        if (selectid.value.length === 0) return ElMessage.warning('请选择要处置的物品！')
        fetch = getGoodsRegAcceptList;
        payload = selectid.value.map(id => ({
          content: {
            remarks: form.remarks,
            creator: {
              id: userInfo.value.userId,
              name: userInfo.value.name,
              organId: userInfo.value.organId || '',
              organName: userInfo.value.organName || ''
            },
            createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
          },
          taskId: id, // 任务ID
          swi: 3 // 流程分支
        }))
      }

      const res: any = await fetch(payload);
      if (res?.code === '1') {
        centerDialogVisible.value = false
        ElMessage.success(tilte.value === '领取物品' ? '已领取!' : '已处置！')
        pager.currentPage = 1;
        loadData();
        computedCount();
      } else {
        ElMessage.error(res?.message || '获取列表失败，请刷新重试！')
      }
    }
  })
}

// 驳回
const handleReject = async (formEl: FormInstance | undefined) => {
  if (!rejectShowRemark.value) {
    form.remarks = '';
    rejectShowRemark.value = true;
    return;
  }
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const payload = {
        content: {
          remarks: form.remarks || '',
          taskId: goodsObject.value?.taskId || "",
          creator: {
            id: userInfo.value.userId,
            name: userInfo.value.name,
            userName: userInfo.value.userName,
            organId: userInfo.value.organId || '',
            organName: userInfo.value.organName || ''
          },
        },
        id: goodsObject.value?.taskId,
        variables: {
          switch: 2,
        }
      }
      const res: any = await processComplete(payload);
      if (res?.code === '1') {
        centerDialogVisible.value = false
        ElMessage.success('已通过!');
        rejectShowRemark.value = false; pager.currentPage = 1;
        loadData();
        computedCount();
      } else {
        ElMessage.error(res?.message || '获取列表失败，请刷新重试！')
      }
    }
  })
}

// 通过
const handleAdopt = async () => {
  const payload = {
    content: {
      taskId: goodsObject?.value?.taskId || "",
      creator: {
        id: userInfo.value.userId,
        name: userInfo.value.name,
        userName: userInfo.value.userName,
        organId: userInfo.value.organId || '',
        organName: userInfo.value.organName || ''
      },
    },
    id: goodsObject.value?.taskId,
    variables: {
      switch: 1,
    }
  }
  const res: any = await processComplete(payload);
  if (res?.code === '1') {
    centerDialogVisible.value = false
    ElMessage.success('已通过!')
    pager.currentPage = 1;
    loadData();
    computedCount();
  } else {
    ElMessage.error(res?.message || '获取列表失败，请刷新重试！')
  }
}

const handleShowBatchDisposal = () => {
  tilte.value = '过期物品批量处置'
  centerDialogVisible.value = true
  defaultButton.value = true;
  dialogWidth.value = '1600px'
  selectid.value = []
}

const handleBatchSelect = (info: any) => {
  if (selectid.value.includes(info.taskId)) {
    selectid.value = selectid.value.filter(item => item !== info.taskId)
  } else {
    selectid.value.push(info.taskId)
  }
}

const computedCount = async () => {
  const res: any = await getGoodsRegFind({ taskProcess: "过期处置,处置审批,回收站,处置审批驳回" });
  if (res?.code === '1') {
    disposalCount.expired = 0;
    disposalCount.approval = 0;
    disposalCount.bin = 0;
    disposalCount.rejection = 0;
    res?.data?.forEach(item => {
      console.log(item)
      if (item.taskProcess === '过期处置') {
        disposalCount.expired += 1;
      }
      if (item.taskProcess === '处置审批') {
        disposalCount.approval += 1;
      }
      if (item.taskProcess === '回收站') {
        disposalCount.bin += 1;
      }
      if (item.taskProcess === '处置审批驳回') {
        disposalCount.rejection += 1;
      }
    })
  }
}


/**
* 获取单位
*/
const getUnit = (val: string) => {
  if (!val) {
    return ''
  } else if (val === 'Y') {
    return '年'
  } else if (val === 'M') {
    return '月'
  } else if (val === 'D') {
    return '天'
  } else if (val === 'H') {
    return '小时'
  }

}
// 获取名称
const getName = (key: string, value: string) => {
  if (key === 'goodsType') {
    let newData = typeData.value.find((item: TypeInter) => item.typeId === value) || {};
    return newData.goodsType || ''
  } else if (key === 'depositPlace') {
    let newData = placeData.value.find((item: TypeInter) => item.value === value) || {};
    return newData.label || ''
  }

}
/**
* 获取类型列表
*/
const getTypeData = async () => {
  const res = await queryGoodsTypeFind()
  let result = res?.data || []
  typeData.value = result;
}

watch(() => taskProcess.value, (val) => {
  pager.currentPage = 1;
  loadData();
})

onBeforeMount(() => {
  loadData();

  loadDict();
  loadDict2();
  getTypeData()

  queryGoodsTypeFind();
  // 获取tab数量
  // timer.value = setInterval(() => computedCount(), 5 * 1000)
  computedCount()
})

onBeforeUnmount(() => {
  // clearInterval(timer.value)
})

</script>

<style lang="less" scoped>
.goods {
  max-height: 450px;
  overflow-y: auto;
  display: flex;
  flex-wrap: wrap;

  .goods_content {
    width: calc(100% / 3 - 24px);
    min-height: 180px;
    background: #F3F4F7;
    border-radius: 8px;
    margin-top: 24px;
    margin-right: 24px;
    display: flex;
    align-items: center;
    position: relative;
    flex-wrap: wrap;
    padding: 24px;
    box-sizing: border-box;

    .image {
      width: 90px;
      height: 90px;
    }

    .message {
      width: calc(100% - 132px - 56px);
      margin-left: 24px;

      .message_content {
        display: flex;
        flex-wrap: wrap;

        .type {
          width: 100%;
            font-size: 16px;
            font-family: HarmonyOS_Sans_SC_Bold;
            color: #535862;
            font-weight: bolder;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .terminal {
          margin-left: 16px;
          display: inline-block;
          text-align: center;
          width: 32px;
          height: 22px;
          line-height: 22px;
          background: rgba(0, 148, 255, 0.12);
          border-radius: 6px;
          border: 1px solid rgba(47, 143, 241, 0.4);
          font-size: 14px;
          color: #2F7DF1;
          ;
        }

        .headline {
          width: 70px;
          height: 22px;
          font-size: 14px;
          font-family: HarmonyOS_Sans_SC;
          color: #989DAA;
          line-height: 22px;
        }

        .headline_content {
          width: 62%;
          height: 22px;
          font-size: 14px;
          font-family: HarmonyOS_Sans_SC;
          color: #535862;
          line-height: 22px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

    }

    .btn-group {
      position: absolute;
      bottom: 24px;
      right: 8px;
      display: flex;
      flex-direction: column;
      /deep/.el-button{
        margin:0;
      }
      /deep/.el-button--primary{
        margin-top: 10px;
      }
    }
  }

  .hidden_overdue {
    display: none;
  }

  .red_overdue {
    height: 28px;
    background: rgba(255, 71, 36, 0.12);
    border-radius: 6px;
    border: 1px solid rgba(255, 76, 45, 0.4);
    font-size: 14px;
    font-family: HarmonyOS_Sans_SC;
    color: #F24A45;
    line-height: 28px;
    padding-left: 8px;
    padding-right: 8px;
    position: absolute;
    top: 8px;
    right: 8px;
  }

  .green_overdue {
    height: 28px;
    background: rgba(255, 179, 31, 0.12);
    border-radius: 6px;
    border: 1px solid rgba(255, 159, 58, 0.4);
    font-size: 14px;
    font-family: HarmonyOS_Sans_SC;
    color: #FF8F3A;
    line-height: 28px;
    padding-left: 8px;
    padding-right: 8px;
    position: absolute;
    top: 8px;
    right: 8px;
  }
}

.detail_content {
  display: flex;
  justify-items: center;
  align-items: center;
  padding: 24px;
  padding-bottom: 0px;

  .content_img {
    width: 240px;
    height: 240px;
  }

  .detail_body {
    width: 448px;
    height: 240px;
    background: rgba(238, 243, 255, 0.56);
    border-radius: 8px;
    margin-left: 24px;
    padding-left: 24px;
    padding-top: 16px;
    padding-bottom: 16px;
    box-sizing: border-box;

    .body_message {
      display: flex;

      .message_title {
        width: 84px;
        text-align: right;
        margin-bottom: 8px;
        font-size: 14px;
        font-family: HarmonyOS_Sans_SC;
        color: #989DAA;
      }

      .message_content {
        font-size: 14px;
        font-family: HarmonyOS_Sans_SC;
        color: #535862;
        margin-left: 10px;
      }
    }
  }
}


// 审批过期物品处置
.dispose-container {
  .title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 15px;
  }

  .content {
    display: flex;
    align-items: flex-start;
    justify-content: center;

    /deep/ .el-carousel {
      width: 240px;
      height: 240px;
      flex-shrink: 0;
      margin-right: 10px;
    }

    img {
      width: 240px;
      height: 240px;
      flex-shrink: 0;
      margin-right: 10px;
    }

    .info {
      background: rgba(238, 243, 255, 0.56);
      flex-grow: 1;
      padding: 16px 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-wrap: wrap;

      .item {
        width: 50%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin-bottom: 8px;

        .label {
          width: 120px;
          text-align: left;
          margin-bottom: 8px;
          font-size: 14px;
          font-family: HarmonyOS_Sans_SC;
          color: #989DAA;
        }

        .value {
          font-size: 14px;
          font-family: HarmonyOS_Sans_SC;
          color: #535862;
          margin-bottom: 8px;
          margin-left: 10px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }

  .info2 {
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;

    .item {
      width: 33%;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin-bottom: 8px;

      .label {
        width: 120px;
        text-align: left;
        margin-bottom: 8px;
        font-size: 14px;
        font-family: HarmonyOS_Sans_SC;
        color: #989DAA;
      }

      .value {
        width: 100%;
        font-size: 14px;
        font-family: HarmonyOS_Sans_SC;
        color: #535862;
        margin-bottom: 8px;
        margin-left: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}


// 批量处置
.batch-check-list {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: wrap;
  margin-bottom: 35px;

  .item {
    display: flex;
    align-items: center;
    justify-content: center;
    width: calc(25% - 10px);
    cursor: pointer;
    padding: 16px 24px;
    box-sizing: border-box;
    border: #dcdfe6 1px solid;
    border-radius: 10px;
    position: relative;
    margin-bottom: 10px;
    margin-right: 10px;

    &:hover {
      background-color: #989DAA0c;
    }


    .check {
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 2;
      background-color: #d7d7d7;
      width: 26px;
      height: 26px;
      padding: 4px;
      border-radius: 50%;
      box-sizing: border-box;
      font-weight: 900;
      color: #fff;
    }

    &.select {
      border: #337eca 1px solid;
      background-color: #337eca10;
      flex: 1;

      .check {
        background-color: #337eca;
      }
    }

    img {
      display: block;
      width: 150px;
      height: 150px;
      flex-shrink: 0;
      flex-grow: 0;
      margin-right: 10px;
    }

    .info {
      flex-grow: 1;
      flex-shrink: 1;
      width: 60%;
      .title {
        width: 100%;
        font-size: 16px;
        font-family: HarmonyOS_Sans_SC_Bold;
        color: #535862;
        font-weight: bolder;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .row {
        display: flex;
        align-items: center;
        justify-content: center;

        .label {
          width: 80px;
          text-align: left;
          margin-bottom: 8px;
          font-size: 14px;
          font-family: HarmonyOS_Sans_SC;
          color: #989DAA;
        }

        .value {
          font-size: 14px;
          font-family: HarmonyOS_Sans_SC;
          color: #535862;
          margin-left: 10px;
          flex-grow: 1;
          color: rgb(51, 126, 202);
        }
      }
    }
  }
}

.status-btn {
  position: absolute;
  right: 15px;
  top: 15px;
}

.badge {
  background-color: #f56c6c;
  border-radius: 10px;
  color: #fff;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  height: 18px;
  padding: 0 6px;
  white-space: nowrap;
  border: 1px solid #fff;
  position: absolute;
  top: 0;
  right: calc(1px + 18px / 2);
  transform: translateY(-50%) translate(100%);
  z-index: 1;
}
</style>
